package tech.popsoft.cip.manage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tech.popsoft.cip.manage.service.ApiAppService;
import tech.popsoft.cip.manage.vo.ApiAppVO;
import tech.popsoft.platform.common.annotation.SystemLog;
import tech.popsoft.platform.common.base.BaseController;
import tech.popsoft.platform.common.enums.LogTypeEnum;
import tech.popsoft.platform.common.query.QueryGenerator;
import tech.popsoft.platform.common.utils.ResultUtil;
import tech.popsoft.platform.common.vo.PageInfo;
import tech.popsoft.platform.common.vo.Result;
import tech.popsoft.platform.common.vo.SortInfo;
import tech.popsoft.cip.manage.entity.ApiApp;

import java.util.ArrayList;
import java.util.List;

/**
 * 应用 前端控制器
 * @author wqliu
 * @date 2021-08-17
 *
 */
@RestController
@RequestMapping("/cip/apiApp")
@Slf4j
public class ApiAppController extends BaseController {
 @Autowired
 private ApiAppService apiAppService;

    //region 基本操作
    /**
     * 初始化
     */
    @ApiOperation(value = "初始化")
    @GetMapping("/init")
    public ResponseEntity<Result> init() {
        ApiApp entity=apiAppService.init();
        ApiAppVO vo = convert2VO(entity);
        return ResultUtil.success(vo);
    }

    /**
     * 新增
     */
    @ApiOperation(value = "新增")
    @PostMapping("/")
    @SystemLog(value = "应用-新增")
    @PreAuthorize("hasPermission(null,'cip:apiApp:add')")
    public ResponseEntity<Result> add(@Validated @RequestBody ApiAppVO vo) {
        ApiApp entity=convert2Entity(vo);
        apiAppService.add(entity);
        ApiAppVO newVO = convert2VO(entity);
        return ResultUtil.success(newVO);
    }

    /**
     * 修改
     */
    @ApiOperation(value = "修改")
    @PutMapping("/")
    @SystemLog(value = "应用-修改")
    @PreAuthorize("hasPermission(null,'cip:apiApp:modify')")
    public ResponseEntity<Result> modify(@Validated @RequestBody ApiAppVO vo)  {
        ApiApp entity=convert2Entity(vo);
        //此处数据库会更新 更新人和更新时间，但数据模型不会刷新
        //个别需展示的该类信息的地方可以重新查询后返回
        apiAppService.modify(entity);
        ApiAppVO newVO = convert2VO(entity);
        return ResultUtil.success(newVO);
    }

    /**
     * 删除数据，单条数据标识，或多条数据标识用逗号间隔拼成的字符串
     */
    @ApiOperation(value = "删除")
    @ApiImplicitParam(name = "id", value = "标识", required = true, dataType = "String",paramType ="path")
    @DeleteMapping("/{id}")
    @SystemLog(value = "应用-删除")
    @PreAuthorize("hasPermission(null,'cip:apiApp:remove')")
    public ResponseEntity<Result> remove(@PathVariable("id") String id) {
        apiAppService.remove(id);
        return ResultUtil.success();
    }

    /**
     * 分页
     */
    @ApiOperation(value = "分页查询")
    @GetMapping("/page")
    @SystemLog(value = "应用-分页")
    @PreAuthorize("hasPermission(null,'cip:apiApp:query')")
    public ResponseEntity<Result> page(ApiAppVO queryVO, PageInfo pageInfo, SortInfo sortInfo) {

        //构造分页对象
        IPage<ApiApp> page = new Page<ApiApp>(pageInfo.getPageNum(), pageInfo.getPageSize());
        //构造查询条件
        QueryWrapper<ApiApp> queryWrapper = QueryGenerator.generateQueryWrapper(ApiApp.class,queryVO,sortInfo);

        //查询数据
        apiAppService.page(page, queryWrapper);
        //转换vo
        IPage<ApiAppVO> pageVO = mapperFacade.map(page, IPage.class);
        List<ApiAppVO>  apiAppVOList=new ArrayList<>();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ApiAppVO vo = convert2VO(page.getRecords().get(i));
            apiAppVOList.add(vo);
        }
        pageVO.setRecords(apiAppVOList);        ;
        return ResultUtil.success(pageVO);
    }


    /**
     * 列表
     */
    @ApiOperation(value = "获取列表")
    @GetMapping("/list")
    @SystemLog(value = "应用-列表")
    @PreAuthorize("hasPermission(null,'cip:apiApp:query')")
    public ResponseEntity<Result> list(ApiAppVO queryVO, SortInfo sortInfo) {
        //构造查询条件
        QueryWrapper<ApiApp> queryWrapper = QueryGenerator.generateQueryWrapper(ApiApp.class, queryVO,sortInfo);
        List<ApiApp> list= apiAppService.list(queryWrapper);
        //转换vo
        List<ApiAppVO>  apiAppVOList=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ApiAppVO vo = convert2VO(list.get(i));
            apiAppVOList.add(vo);
        }
        return ResultUtil.success(apiAppVOList);
    }

    /**
     * 获取单条数据
     */
    @ApiOperation(value = "获取单条数据")
    @ApiImplicitParam(name = "id", value = "标识", required = true, dataType = "String",paramType ="path")
    @GetMapping("/{id}")
    @SystemLog(value = "应用-详情")
    @PreAuthorize("hasPermission(null,'cip:apiApp:view')")
    public ResponseEntity<Result> get(@PathVariable("id") String id) {
        ApiApp entity = apiAppService.query(id);
        ApiAppVO vo = convert2VO(entity);
        return ResultUtil.success(vo);
    }

    //endregion

    //region 扩展操作
    /**
     * 启用
     */
    @ApiOperation(value = "启用")
    @PutMapping("/{id}/enable")
    @ApiImplicitParam(name = "id", value = "标识", required = true, dataType = "String", paramType = "path")
    @SystemLog(value = "应用-启用")
    @PreAuthorize("hasPermission(null,'cip:apiApp:enable')")
    public ResponseEntity<Result> enable(@PathVariable("id") String id) {

        apiAppService.enable(id);
        return ResultUtil.success();
    }

    /**
     * 停用
     */
    @ApiOperation(value = "停用")
    @PutMapping("/{id}/disable")
    @ApiImplicitParam(name = "id", value = "标识", required = true, dataType = "String", paramType = "path")
    @SystemLog(value = "应用-停用")
    @PreAuthorize("hasPermission(null,'cip:apiApp:disable')")
    public ResponseEntity<Result> disable(@PathVariable("id") String id) {

        apiAppService.disable(id);
        return ResultUtil.success();
    }

    /**
     * 管理员重置密钥
     */
    @ApiOperation(value = "管理员重置密钥", notes = "管理员重置密钥")
    @ApiImplicitParam(name = "id", value = "标识", required = true, dataType = "String", paramType = "path")
    @PutMapping("/{id}/resetSecret")
    @SystemLog(value = "重置密码", logType = LogTypeEnum.AUDIT)
    @PreAuthorize("hasPermission(null,'cip:apiApp:resetSecret')")
    public ResponseEntity<Result> resetPassword(@PathVariable String id) {
        apiAppService.resetSecret(id);
        return ResultUtil.success();
    }


    //endregion

    //region 接口服务权限

    /**
     * 授予接口服务权限
     */
    @PutMapping("/{appId}/grantApiPermission")
    @SystemLog(value = "应用-授予接口服务权限")
    @PreAuthorize("hasPermission(null,'cip:apiApp:grantApiPermission')")
    public ResponseEntity<Result> grantApiPermission(@PathVariable String appId,
                                                     @RequestParam(required = false) List<String> apiServiceIdList) {
        apiAppService.grantApiPermission(appId, apiServiceIdList);
        return ResultUtil.success();
    }

    /**
     * 收回接口服务权限
     */
    @PutMapping("/{appId}/withdrawApiPermission")
    @SystemLog(value = "应用-收回接口服务权限")
    @PreAuthorize("hasPermission(null,'cip:apiApp:withdrawApiPermission')")
    public ResponseEntity<Result> withdrawApiPermission(@PathVariable String appId, @RequestParam(required = false) List<String> apiServiceIdList) {
        apiAppService.withdrawApiPermission(appId, apiServiceIdList);
        return ResultUtil.success();
    }


    //endregion

    //region 消息主题权限

    /**
     * 授予消息主题权限
     */
    @PutMapping("/{appId}/grantMessageTopicPermission")
    @SystemLog(value = "应用-授予消息主题权限")
    @PreAuthorize("hasPermission(null,'cip:apiApp:grantMessageTopicPermission')")
    public ResponseEntity<Result> grantMessageTopicPermission(@PathVariable String appId,
                                                     @RequestParam(required = false) List<String> apiMessageTopicIdList) {
        apiAppService.grantMessageTopicPermission(appId, apiMessageTopicIdList);
        return ResultUtil.success();
    }

    /**
     * 收回消息主题权限
     */
    @PutMapping("/{appId}/withdrawMessageTopicPermission")
    @SystemLog(value = "应用-收回消息主题权限")
    @PreAuthorize("hasPermission(null,'cip:apiApp:withdrawMessageTopicPermission')")
    public ResponseEntity<Result> withdrawMessageTopicPermission(@PathVariable String appId, @RequestParam(required = false) List<String> apiMessageTopicIdList) {
        apiAppService.withdrawMessageTopicPermission(appId, apiMessageTopicIdList);
        return ResultUtil.success();
    }


    //endregion





    //region 辅助操作

    private ApiAppVO convert2VO(ApiApp entity){
        ApiAppVO vo=mapperFacade.map(entity,ApiAppVO.class);
        String statusName = dictionaryUtil.getNameByCode("Status", entity.getStatus());
        vo.setStatusName(statusName);
        String integrationModelName = dictionaryUtil.getNameByCode("IntegrationModel", entity.getIntegrationModel());
        vo.setIntegrationModelName(integrationModelName);
        return vo;
    }

    private ApiApp convert2Entity(ApiAppVO vo){

        ApiApp entity=mapperFacade.map(vo,ApiApp.class);
        return entity;
    }

   //endregion
}
